/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package core.net;

import core.pojos.OneDriveItem;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import static java.lang.System.out;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.codehaus.jackson.map.ObjectMapper;
import org.scribe.model.Token;

/**
 *
 * @author royal
 */


public class OnedriveRequest {

    private static final String OauthUrl = "https://login.live.com/oauth20_authorize.srf";
    private static final String CLIENT_ID = "00000000481144DE";
    private static final String REDIRECT_URI = "https://login.live.com/oauth20_desktop.srf";
    private static final String CLIENT_SECRET = "B3BnnqsuUv1K9y4uAh8i9FRfKysZHaLs";
     private static final String ROOT_META = "https://apis.live.net/v5.0/";

         // access token
    private final Token token;

    public OnedriveRequest(Token token) {
        this.token = token;
    }
     
     
    /**
     * Retrieves file and folder metadata
     *
     * @param path The relative path to the file or folder
     * @return JSON String
     * @throws URISyntaxException Invalid URI
     * @throws IOException Bad request
     */
    public String getRequestToken() throws URISyntaxException, IOException {
        URI uri = Param.create()
                .setUrl(OauthUrl)
                .setParam("client_id", CLIENT_ID)
                .setParam("scope", "wl.offline_access")
                .setParam("response_type", "code")
                .setParam("redirect_uri", REDIRECT_URI)
                .buildURI();

        /*return Request.Get(uri)
         .execute()
         .returnContent().asString();*/
        return uri.toString();

    }

    public String getAccesstToken(String code) throws URISyntaxException, IOException {
        URI uri = Param.create()
                .setUrl("https://login.live.com/oauth20_token.srf")
                .setParam("client_id", CLIENT_ID)
                .setParam("client_secret", CLIENT_SECRET)
                .setParam("grant_type", "authorization_code")
                .setParam("code", code)
                .setParam("redirect_uri", REDIRECT_URI)
                .buildURI();

        return Request.Post(uri)
                .execute()
                .returnContent().asString();
        //return uri.toString();

    }

//    public static void main(String[] args) throws URISyntaxException, IOException, Exception {
//        Scanner in = new Scanner(System.in);
//
//        OnedriveRequest req = new OnedriveRequest();
//        System.out.println(req.getRequestToken());
//
//        String code = in.nextLine();
//        System.out.println();
//
//        System.out.println("Exchange the Request Token for an Access Token...");
//        req.sendPost(code);
//    }

    // HTTP POST request
    private void sendPost(String code) throws Exception {
        String url = "https://login.live.com/oauth20_token.srf";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        String urlParameters = "client_id=" + CLIENT_ID
                + "&redirect_uri=" + REDIRECT_URI
                + "&client_secret=" + CLIENT_SECRET
                + "&code=" + code
                + "&grant_type=authorization_code";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }
    
        /**
     * Retrieves file and folder metadata
     *
     * @param path The relative path to the file or folder
     * @return JSON String
     * @throws URISyntaxException Invalid URI
     * @throws IOException Bad request
     */
    public String list(String path) throws URISyntaxException, IOException {

        if (path == null || path.trim().length() == 0) {
            path = ROOT_META +"me/skydrive";
        }else{
        path = ROOT_META + path +"/files";
        }
        URI uri = Param.create()
                .setToken(token)
                .setUrl(path)
                .buildURI();
        return Request.Get(uri)
                .execute()
                .returnContent().asString();
    }
    
            /**
     * Downloads a file
     *
     * @param path The relative path to the file you want to retrieve
     * @param out Output stream to write downloaded file
     * @throws URISyntaxException
     * @throws IOException
     */
    
        public void download(String path, OutputStream out) throws URISyntaxException, IOException {

        path = ROOT_META + path +"/content";
        
        URI uri = Param.create()
                .setToken(token)
                .setUrl(path)
                .buildURI();
        
        byte[] data = Request.Get(uri)
                .execute().returnContent().asBytes();
        out.write(data);
        
        }
    
}
